<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 新中天3 ajie
 */
class Xinzt3Controller extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.ordNo") ? I("request.ordNo") : I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        // $isMobile = isMobile();
        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']){
            case 17:
            case 18:
                $pay_bankcode = 'alih5';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }


        $params = [
            "amount_fee"=>number_format($return['amount'],2,'.',''),
            "out_order_sn"=>$return['orderid'],
            "title"=>"订单支付",
            "mch_id"=>$this->config['mch_id'],
            "sign_type"=>"MD5",
            "attach"=>"wlf",
            "notify_url"=> $return['notifyurl'],
            "return_url"=>$return['callbackurl'],
            "nonce_str"=>rand(111111,9999999),
            "pay_type"=>$pay_bankcode
        ];

        ksort($params);
        reset($params);

        $str = httpstr($params) . "&key=".$this->config['signkey'];
        $params['sign'] = strtoupper(md5($str));


        $res = curl($this->config['gateway'].'/unifiOrder', httpstr($params));//curl_post
        $resp = json_decode($res,true);

       // var_dump('<pre/>',$params,$res,$resp);exit();


        if(empty($resp["token_id"])){
            if($resp['err_msg']){
                $this->showmessage($resp['err_msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付连接失败！',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $code = $this->config['gateway']."/pay?token_id=".$resp["token_id"];
        header("Location: {$code}");

        exit();
    }



    //通知
    public function notifyurl(){
        //$this->debug_callback();

        //IP白名单
        if(!$this->checkip(getIP(),['154.83.14.167'])){
            exit("wrong");
        }

        $p = I("post.");

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['out_trade_no'];

        //获取订单
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "pay_orderid_rd"=> htmlspecialchars($p['transaction_sn'])
        ));


        $real_amount =  $p['real_amount_fee']/100;     //实际支付金额
        $pay_amount =  $find['pay_amount']; //商户提交订单金额

        if(abs($real_amount - $pay_amount) > 0.1){
            echo 'wrong_money'; exit;
        }

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>$this->class]);

        $sign = $p['sign'];
        unset($p['sign']);

        ksort($p);
        reset($p);

        $str = "";
        foreach($p as $k=>$v){
            if($v !== ''){
                $str .= "{$k}={$v}&";
            }
        }

        $str = $str . "key=".$this->config['signkey'];
        $sign2 = strtoupper(md5($str));

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['result_code'] !== '0'){
            exit("pay_fail");
        }


        $this->async($find['pay_orderid'],"success");
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}
